package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.GoodsModel;
import com.tiantianyuegou.model.TuanGouGoodsAdapter;
import com.tiantianyuegou.model.TuanGouGoodsInfo;
import com.tiantianyuegou.model.TuanGouInfo;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.TimeUtil;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.view.NoScrollGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 团购热抢商品详情
 * Created by Administrator on 2016/1/13.
 */
public class TuangouStoreDetailActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    ImageView ivback, iv_tuanGouInfo;
    NoScrollGridView grid_tuangougoods;
    TextView tv_day, tv_hours, tv_minutes, tv_title;
    Timer timer;
    TimerTask timerTask;
    private String mCountTime;
    List<GoodsModel> data;
    TuanGouInfo tuanGouInfo;
    String startTime, endTime;
    long ttStart;
    private boolean isRefresh = true;
    private boolean isLoadmore = false;
    int mPage = 1;
    PullToRefreshScrollView mScrollView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuangoustoredetail);
        initViews();
    }


    @Override
    public void findViewByIds() {
        ivback = (ImageView) findViewById(R.id.back);
        iv_tuanGouInfo = (ImageView) findViewById(R.id.iv_tuanGouInfo);
        tv_day = (TextView) findViewById(R.id.tv_day);
        tv_hours = (TextView) findViewById(R.id.tv_hours);
        tv_minutes = (TextView) findViewById(R.id.tv_minutes);
        tv_title = (TextView) findViewById(R.id.tv_title);
        mScrollView = (PullToRefreshScrollView) findViewById(R.id.scroll_tuangou);
        grid_tuangougoods = (NoScrollGridView) findViewById(R.id.grid_tuangougoods);

        tuanGouInfo = new TuanGouInfo();
        tuanGouGoodsInfoList = new ArrayList<>();
        tuanGouInfo = (TuanGouInfo) getIntent().getSerializableExtra("tuanGouInfo");
        tv_title.setText(tuanGouInfo.getTtTitle());
        ImageLoader.getInstance().displayImage(tuanGouInfo.getTtPic(), iv_tuanGouInfo);
        long ttEnd = tuanGouInfo.getTtEnd();
        ttStart = tuanGouInfo.getTtStart();
        endTime = TimeUtils.convertTimeYMDHMS(ttEnd);
        startTime = TimeUtils.convertTimeYMDHMS(ttStart);

        loadingDialog = new LoadingDialog(TuangouStoreDetailActivity.this);
        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        doTuanGouDetail(mPage);//团购详情接口

    }

    LoadingDialog loadingDialog;
    List<TuanGouGoodsInfo> tuanGouGoodsInfoList;

    private void doTuanGouDetail(int page) {
        if (!NetworkUtils.isNetworkAvailable(TuangouStoreDetailActivity.this)) {
            TuangouStoreDetailActivity.this.showMsg("请检查网络");
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", "" + page);
        params.addBodyParameter("ttId", "" + tuanGouInfo.getTtID());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.TEAM_BUY_DETAIL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mScrollView.onRefreshComplete();
                System.out.println(responseInfo.result + "");
                loadingDialog.dismiss();
                String returnStr = responseInfo.result;
                try {
                    JSONObject returnObj = new JSONObject(returnStr);
                    int code = returnObj.getInt("code");
                    if (code == 100) {
                        if (isRefresh) {
                            tuanGouGoodsInfoList.clear();
                            isRefresh = false;
                        }
                        if (isLoadmore) {
                            isLoadmore = false;
                        }
                        String list = returnObj.getString("list");
                        if (list.contains("[")) {
                            JSONArray listArr = new JSONArray(list);
                            for (int i = 0; i < listArr.length(); i++) {
                                JSONObject strObj = listArr.getJSONObject(i);
                                int tpId = strObj.getInt("tpId");
                                String tpName = strObj.getString("tpName");
                                double tpSalePrice = strObj.getDouble("tpSalePrice");
                                double tpTuangouProce = strObj.getDouble("tpTuangouProce");
                                int tpTuangouStore = strObj.getInt("tpTuangouStore");
                                int tpRedCount = strObj.getInt("tpRedCount");
                                int tpSalesCount = strObj.getInt("tpSalesCount");
                                String tpPics = strObj.getString("tpPic");
                                String tpPic = tpPics.split(",")[0];
                                TuanGouGoodsInfo tuanGouGoodsInfo = new TuanGouGoodsInfo(tpId, tpName, tpSalePrice, tpTuangouProce, tpTuangouStore, tpRedCount, tpSalesCount, tpPic);
                                tuanGouGoodsInfoList.add(tuanGouGoodsInfo);
                            }
                            System.out.println("---------" + tuanGouGoodsInfoList.size() + "---------");
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        if (isRefresh) {
                            isRefresh = false;
                        }
                        if (isLoadmore) {
                            isLoadmore = false;
                            showMsg("没有更多数据");
                            mPage--;
                            mScrollView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
                        }
                    }


                } catch (JSONException e) {
                    if (isRefresh) {
                        isRefresh = false;
                    }
                    if (isLoadmore) {
                        isLoadmore = false;
                        mPage--;
                    }
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mScrollView.onRefreshComplete();
                loadingDialog.dismiss();
                showMsg("请求服务器失败");
                if (isRefresh) {
                    isRefresh = false;
                }
                if (isLoadmore) {
                    isLoadmore = false;
                    mPage--;
                }
            }
        });

    }


    @Override
    public void initListener() {
        ivback.setOnClickListener(this);
        grid_tuangougoods.setOnItemClickListener(this);
        mScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                isRefresh = true;
                isLoadmore = false;
                mScrollView.setMode(PullToRefreshBase.Mode.BOTH);
                doTuanGouDetail(mPage);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                isRefresh = false;
                isLoadmore = true;
                doTuanGouDetail((++mPage));
            }
        });

    }

    TuanGouGoodsAdapter adapter;

    @Override
    public void initData() {
        adapter = new TuanGouGoodsAdapter(TuangouStoreDetailActivity.this, tuanGouGoodsInfoList);

        grid_tuangougoods.setAdapter(adapter);
        timeCountDown();//倒计时

    }

    private void timeCountDown() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //初始化结束时间
        TimeUtil.initCountDown(endTime);
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
        super.onDestroy();
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        }
    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            mCountTime =TimeUtil.execCountDown();
            String[] times = mCountTime.split(":");
//            timeView.setText(mCountTime);
            tv_day.setText(times[0]);
            tv_hours.setText(times[1]);
            tv_minutes.setText(times[2]);
            //倒计时结束
            if ("00:00:00:00".equals(mCountTime)) {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                if (timerTask != null) {
                    timerTask = null;
                }
            }
        }
    };


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        Intent intent = new Intent(TuangouStoreDetailActivity.this, GoodsDetailActivity.class);
        String tpid = ""+tuanGouGoodsInfoList.get(position).getTpId();
        String tpPic=tuanGouGoodsInfoList.get(position).getTpPic();
        intent.putExtra("tpId", tpid);
        intent.putExtra("tpPic", tpPic);
        intent.putExtra("type","TuangouStoreDetailActivity");
        System.out.println("------------------" + tpid+ "------------------" + tpPic + "------------------");
        startActivity(intent);

    }
}
